﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace Sendz.Validators
{
    public class RequiredWhenContainsValidator : DataAnnotationsModelValidator<RequiredWhenContainsAttribute>
    {
        public RequiredWhenContainsValidator(ModelMetadata metadata, ControllerContext context, RequiredWhenContainsAttribute attribute)
            : base(metadata, context, attribute) { }

        public override IEnumerable<ModelValidationResult> Validate(object container)
        {
            // Get a reference to the property this validation depends upon
            var field = Metadata.ContainerType.GetProperty(Attribute.DependentProperty);

            if (field != null)
            {
                // Get the value of the dependent property
                var value = field.GetValue(container, null);

                // Compare the value against the target value
                if ((value == null && Attribute.TargetValue == null) ||  
                    (value != null && value.ToString().ToLowerInvariant().IndexOf(Attribute.TargetValue.ToString().ToLowerInvariant()) > -1))
                {
                    if (Metadata.Model != null)
                    {
                        // Sometimes an array will be used since the ViewModel may capture multiple-item values in an array, so check for that
                        var thisVal = (Metadata.Model.GetType().ToString() == "System.String[]") ? string.Join(string.Empty, ((string[])Metadata.Model)) : (string)Metadata.Model;

                        if (string.IsNullOrWhiteSpace(thisVal)) // !Attribute.IsValid(Metadata.Model)
                            // Validation failed - return an error
                            yield return new ModelValidationResult { Message = ErrorMessage };
                    }
                    else
                    {
                        yield return new ModelValidationResult { Message = ErrorMessage };
                    }
                }
            }
        }
        // No client-side needed with MVC Roundtrip validation! :)
    }
}
